package com.ericsson.enap.modules.kpi.task.ims;

import com.ericsson.common.quartz.task.ManualTask;
import com.ericsson.common.util.LogFileName;
import com.ericsson.common.util.LoggerUtils;
import com.ericsson.enap.modules.kpi.entity.EnipKpiAlarm;
import com.ericsson.enap.modules.kpi.entity.EnipKpiParam;
import com.ericsson.enap.modules.kpi.entity.KpiDetail;
import com.ericsson.enap.modules.kpi.service.EnipKpiAlarmService;
import com.ericsson.enap.modules.kpi.service.EnipKpiParamService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
public class ParamCompareValueTask implements ManualTask {
    private Logger log = LoggerUtils.Logger(LogFileName.ParamCompareValueJob);
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private EnipKpiParamService enipKpiParamService;
    @Autowired
    private EnipKpiAlarmService enipKpiAlarmService;

    public Integer[] netTypes = new Integer[]{101,102,103}; //需要查询的网元类型

    public Integer[] bizTypes = new Integer[]{6,8};  // 业务类型
    @Override
    public void execute() {

        for(Integer bizType : bizTypes) {
            EnipKpiParam kpiParam = new EnipKpiParam();
            kpiParam.setBiztype(bizType);
            Map<String,EnipKpiParam> paramMap = enipKpiParamService.findList(kpiParam).stream().collect(Collectors.toMap(EnipKpiParam::getKpi, enipKpiParam->enipKpiParam));
            if(paramMap != null && paramMap.size() > 0) {
                for(Integer netType : netTypes) {
                    List<KpiDetail> kpiList = searchMaxTime(getCollectionName(netType,String.valueOf(bizType)));
                    if(kpiList.size() > 0) {
                        Optional<KpiDetail> op =  kpiList.stream().max(Comparator.comparing(KpiDetail::getDateTime));
                        String maxTime = op.get().getDateTime();
                        kpiList = kpiList.stream().filter(x -> maxTime.equals(x.getDateTime())).collect(Collectors.toList());
                        for(int i=0; i<kpiList.size(); i++) {
                            for(int j=i+1; j<kpiList.size(); j++) {
                                KpiDetail first = kpiList.get(i);
                                KpiDetail second = kpiList.get(j);
                                Map<String, String> firstKpiMap = first.getKpiMap();
                                Map<String, String> secondKpiMap = second.getKpiMap();
                                for(String key : firstKpiMap.keySet()) {
                                    if(secondKpiMap.get(key) != null) {
                                        EnipKpiParam param = paramMap.get(key);
                                        if(param != null && null != param.getCompareFlag() && !"".equals(param.getCompareFlag()) && param.getCompareFlag() == 1) {
                                            String firstKpiVal = firstKpiMap.get(key);
                                            String secondKpiVal = secondKpiMap.get(key);
                                            double diff = Math.abs(Double.parseDouble(firstKpiVal) - Double.parseDouble(secondKpiVal));
                                            if(param.getCompareValue() != null && !"".equals(param.getCompareValue())) {
                                                if(diff > Double.parseDouble(param.getCompareValue())) {
                                                    //存数据库
                                                    EnipKpiAlarm alarm = new EnipKpiAlarm();
                                                    alarm.setKpi(Integer.parseInt(key));
                                                    alarm.setNetType(Integer.parseInt(param.getKpitype()));
                                                    alarm.setFirstNetid(Integer.parseInt(first.getNetid()));
                                                    alarm.setFirstValue(firstKpiVal);
                                                    alarm.setSecondNetid(Integer.parseInt(second.getNetid()));
                                                    alarm.setSecondValue(secondKpiVal);
                                                    alarm.setDiffValue(""+diff);
                                                    alarm.setDateTime(first.getDateTime());
                                                    alarm.setBizType(bizType);
                                                    List<EnipKpiAlarm> result = enipKpiAlarmService.selectEnipKpiAlarm(alarm);
                                                    if(result.size() <= 0) {
                                                        enipKpiAlarmService.insertEnipKpiAlarm(alarm);
                                                    }

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
    }

    public static String getCollectionName(int netType,String biztype) {
        String collectionName = null;
        if(netType ==101) {
            collectionName="imskpi_"+biztype+"_psbcc";
        } else if(netType ==102) {
            collectionName="imskpi_"+biztype+"_tas";
        } else if(netType ==103) {
            collectionName="imskpi_"+biztype+"_cscf";
        }
        return collectionName;
    }

    public List<KpiDetail> searchMaxTime(String collectionName) {

        /*List<AggregationOperation> operations = new ArrayList<>();
        operations.add(Aggregation.project("netid","dateTime","kpiMap"));
        operations.add(Aggregation.group("netid").first("netid").as("netid").max("dateTime").as("dateTime").
                first("kpiMap").as("kpiMap"));
        Aggregation aggregation = Aggregation.newAggregation(operations);
        AggregationResults<KpiDetail> results = mongoTemplate.aggregate(aggregation, collectionName, KpiDetail.class);
        List<KpiDetail> list = results.getMappedResults();*/
        List<KpiDetail> result = new ArrayList<>();

        List<AggregationOperation> operations = new ArrayList<>();
        operations.add(Aggregation.group("netid").first("netid").as("netid").max("dateTime").as("dateTime"));
        Aggregation aggregation = Aggregation.newAggregation(operations);
        AggregationResults<KpiDetail> results = mongoTemplate.aggregate(aggregation, collectionName, KpiDetail.class);
        List<KpiDetail> list = results.getMappedResults();
        for(KpiDetail detail : list) {
            Query query = new Query(Criteria.where("netid").is(detail.getNetid()).andOperator(Criteria.where("dateTime").is(detail.getDateTime())));
            List<KpiDetail> subList = mongoTemplate.find(query,KpiDetail.class, collectionName);
            result.addAll(subList);
        }
        return result;
    }

}
